package com.jeremyfeinstein.utils;

import android.content.Context;
import android.net.TrafficStats;
import android.util.Log;

public class NetSpeedUtil {
    private static long lastTotalRxBytes = 0;
    private static long lastTimeStamp = 0;

    public static long getNetSpeed(Context mContext) {
        long nowTotalRxBytes = getTotalRxBytes(mContext);
        long nowTimeStamp = System.currentTimeMillis();
        long speed = 0;

        if (nowTimeStamp != lastTimeStamp) {
            // 毫秒转换
            speed = ((nowTotalRxBytes - lastTotalRxBytes) * 1000 / (nowTimeStamp - lastTimeStamp));
        }
        lastTimeStamp = nowTimeStamp;
        lastTotalRxBytes = nowTotalRxBytes;

        return speed;
    }

    private static long getTotalRxBytes(Context mContext) {
        // 转为KB
        return TrafficStats.getUidRxBytes(mContext.getApplicationInfo().uid) == TrafficStats.UNSUPPORTED ? 0
                : (TrafficStats.getTotalRxBytes() / 1024);
    }

}
